package com.banshuibao.bsb_android.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import droidninja.filepicker.cursors.DocScannerTask;
import droidninja.filepicker.cursors.loadercallbacks.FileResultCallback;
import droidninja.filepicker.models.Document;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by zyh on 2017/4/14.
 */

public class FileUtil {

    public final static String DOWN_DIR_NAME = "banshuibao_Download";

    public static String getDirDownloadPath(Context context) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            XToast.showToast(context, "SD卡不存在");
            return "";
        }
        String dir = Environment.getExternalStorageDirectory().getPath() + "/";
        File file = new File(dir + DOWN_DIR_NAME);
        if (!file.exists())
            file.mkdir();
        return file.getPath();
    }

    /**
     * 刷新sd卡
     */
    public static void fileScan(Context context) {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
    }

    /**
     * 打开dox,docx的文件列表
     */
    public static void selectFileDoc(Activity context, FileResultCallback<Document> callBack) {
        new DocScannerTask(context, callBack).execute();
    }

    /**
     * 获取网络中的文件保存到本地
     **/
    public static boolean saveDownloadFile(Response response, String savePath, String fileName) throws Exception {
        if (TextUtils.isEmpty(savePath) || TextUtils.isEmpty(fileName) || response == null) {
            return false;
        }
        InputStream inputStream = getInputStreamFromResponse(response);
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        FileOutputStream fos = new FileOutputStream(savePath + "/" + fileName);
        byte[] data = new byte[10240];

        int len;
        while ((len = bis.read(data)) != -1) {
            fos.write(data, 0, len);
        }
        fos.flush();
        fos.close();
        bis.close();
        return true;
    }

    private static InputStream getInputStreamFromResponse(Response response) throws IOException {
        if (response != null && response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                return responseBody.byteStream();
            }
        }
        return null;
    }

}
